import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import Link from 'umi/link';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import {
  Card,
  Form,
  Icon,
  Badge,
  Radio,
  List,
  Pagination,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './TableList.less';

const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['正常', '关怀中'];

/* eslint react/no-multi-comp:0 */
export default
@connect(({ post, loading }) => ({
  postList: post.list,
  postType: post.postType,
  loading: loading.effects['post/list']
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    isWide: true,
  };

  columns = [
    {
      title: '标题',
      dataIndex: 'post_title',
    },
    {
      title: '发布时间',
      dataIndex: 'post_created',
      render: val => <span>{moment.unix(val).format('YYYY-MM-DD HH:mm')}</span>,
    },
    {
      title: '关怀人数',
      dataIndex: 'post_track_num',
      render: val => `${val || 0}`,
    },
    {
      title: '最近状态',
      render(val, record) {
        if(record.post_status === '-1') {
          return <Badge status="error" text="未支付" />;
        }
        const trackStatus = record.post_last_tracked ? 1 : 0;
        return <Badge status={statusMap[trackStatus]} text={status[trackStatus]} />;
      },
    },
    {
      title: '最近关怀时间',
      dataIndex: 'post_last_tracked',
      render: val => val ? <span>{moment.unix(val).format('YYYY-MM-DD HH:mm')}</span> : '暂无',
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <Link to={`/list/info/${record.post_id}`}>详情</Link>
          <Link to={`/list/detail/${record.post_id}`} style={{marginLeft: 8}}>关怀信息</Link>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch, postType } = this.props;
    dispatch({
      type: 'post/fetch',
      payload: {
        post_type: postType,
      },
    });

    this.setWindowWide();
    window.addEventListener('resize', this.setWindowWide);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.setWindowWide);
    this.setWindowWide.cancel();
  }

  @Bind()
  @Debounce(200)
  setWindowWide() {
    const w = window.innerWidth || document.documentElement.clientWidth;
    this.setState({
      isWide: w > 600,
    });
  }

  handleChangeType = (e) => {
    const { dispatch } = this.props;
    dispatch({type: 'post/savePostType', payload: e.target.value});
    dispatch({
      type: 'post/fetch',
      payload: {
        post_type: e.target.value,
      },
    });
  }

  handleChangeMobilePage = (current) => {
    const { dispatch, postType } = this.props;
    dispatch({
      type: 'post/fetch',
      payload: {
        post_type: postType,
        p: current,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch, postType } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      post_type: postType,
      p: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'post/fetch',
      payload: params,
    });
  };

  render() {
    const {
      postList,
      loading,
      postType,
    } = this.props;
    const {isWide} = this.state;
    return (
      <PageHeaderWrapper title="我的已发记录">
        <Card>
          <div className={styles.tableList}>
            <div className={styles.tableListForm} style={{marginBottom: 8}}>
              <RadioGroup onChange={this.handleChangeType} value={postType}>
                <RadioButton value="0"><Icon type="red-envelope" theme="outlined" /> 红包</RadioButton>
                <RadioButton value="1"><Icon type="video-camera" theme="outlined" /> 视频</RadioButton>
                <RadioButton value="2"><Icon type="file-text" theme="outlined" /> 文件</RadioButton>
                <RadioButton value="3"><Icon type="picture" theme="outlined" /> 图片</RadioButton>
              </RadioGroup>
            </div>
            {isWide ? <StandardTable
              rowKey="post_id"
              selectedRows={[]}
              loading={loading}
              data={postList}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
            /> :
            <div>
              <List
                itemLayout="vertical"
                pagination={false}
                dataSource={postList.list}
                renderItem={item=> (
                  <List.Item
                    className={styles.listItem}
                    key={item.post_id}
                    actions={[]}
                    extra={<Link to={`/list/detail/${item.post_id}`} className={styles.listLink}><div className={styles.listIcon}><Icon type="environment" /><div className={styles.listValue}>{item.post_track_num}</div></div></Link>}
                  >
                    <Link to={`/list/info/${item.post_id}`} className={styles.listLink}>
                      <div className={styles.listTitle}>{item.post_title}</div>
                      <div className={styles.listDate}>{`发布时间：${moment.unix(item.post_created).format('YYYY-MM-DD HH:mm')}`}</div>
                    </Link>
                  </List.Item>
                )}
              />
              <div style={{textAlign: 'right', marginTop: 8}}>
                <Pagination current={postList.pagination.current} total={postList.pagination.total} onChange={this.handleChangeMobilePage} />
              </div>
            </div>
            }
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
